const std = @import("std");
const Cell = @import("../cell.zig");
const Food = @import("../map/food.zig");
const IndexBlock = @import("../map/index_block.zig");

pub fn scanAndDo(cell: *Cell) void {
    scanGridCell(cell.index_block, cell);
    scanGridCell(cell.index_block.up, cell);
    scanGridCell(cell.index_block.right, cell);
    scanGridCell(cell.index_block.right_down, cell);
    scanGridCell(cell.index_block.down, cell);
    scanGridCell(cell.index_block.left_down, cell);
    scanGridCell(cell.index_block.left, cell);
    scanGridCell(cell.index_block.left_up, cell);
}

fn scanGridCell(index_block: ?*IndexBlock, cell: *Cell) void {
    if (null != index_block) {
        var food_iter = index_block.?.food_set.valueIterator();
        while (food_iter.next()) |food| {
            if (distance(cell, Food, food.*) <= cell.scan_range) {
                cell.eat(food.*);
            }
        }

        var cell_iter = index_block.?.cell_set.valueIterator();
        while (cell_iter.next()) |enemy| {
            if (cell != enemy.*) {
                if (distance(cell, Cell, enemy.*) <= cell.scan_range) {
                    // cell.fight(enemy.*);
                }
            }
        }
    }
}

fn distance(cell: *Cell, comptime T: type, target: *T) f32 {
    const dx = cell.x - target.x;
    const dy = cell.y - target.y;

    return std.math.sqrt(dx * dx + dy * dy);
}
